package com.example.demo.until;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: hhl
 * @createDate: 2023/6/29
 * @version: 1.0
 */
public class BlockingQueue<T> {
    //队列
    private Deque<T> queue = new ArrayDeque<>();
    //容量
    private Integer capcity;
    //锁
    private ReentrantLock lock = new ReentrantLock();
    //生成者条件变量
    private Condition fullWaitSet = lock.newCondition();
    //消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();

    public BlockingQueue(Integer capcity) {
        this.capcity = capcity;
    }

    //超时时阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        // 将 timeout 统一转换为 纳秒
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    if (timeout < 0) {
                        return null;
                    }
                    emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        }finally {
            lock.unlock();
        }
    }

    // 带超时时间阻塞添加
    public Boolean Offer(T task,long timeout, TimeUnit unit){
        lock.lock();
        try{
            Long nanos = unit.toNanos(timeout);
            while (queue.size() == capcity){
               try{
                   if(nanos < 0){
                       return false;
                   }
                   nanos = fullWaitSet.awaitNanos(nanos);
               }catch(InterruptedException e){
                   e.printStackTrace();
               }
            }
            queue.addLast(task);
            emptyWaitSet.signal();
            return true;
        }finally {
            lock.unlock();
        }
    }

    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }
    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            // 判断队列是否满
            if(queue.size() == capcity) {
                rejectPolicy.reject(this, task);
            } else { // 有空闲
//                log.debug("加入任务队列 {}", task);
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
